import fs from "fs";
import path from "path";
import "reflect-metadata";
import { Request, Response, NextFunction } from "express";
// import { controller, use, get } from "./decorator";  //该引用方式已被弃用
import { controller, use, get } from "../decorator";
import { getResponseData } from "../utils/util";
// 引入爬虫
import Crowller from "../utils/crowller";
// 引入分析器
import LycAnalyzer from "../utils/analyzer";

interface bodyRequest extends Request {
  body: { [key: string]: string | undefined };
}

// 自己编写登录权限校验的中间件
const checkLogin = (
  req: bodyRequest,
  res: Response,
  next: NextFunction
): void => {
  const isLogin = !!(req.session ? req.session.login : false);
  if (isLogin) {
    next();
  } else {
    // 返回标准接口定义的数据类型
    res.json(getResponseData(null, `请先登录`));
  }
};

const test = (req: bodyRequest, res: Response, next: NextFunction): void => {
  console.log("test middleware");
  next();
};

@controller("/")
export class CrowllerController {
  @get("/getData")
  // 添加中间件装饰器
  @use(checkLogin)
  // 测试一个方法用两次同一个装饰器方法
  @use(test)
  getData(req: bodyRequest, res: Response): void {
    const url = `https://www.imooc.com/`;
    const analyzer = LycAnalyzer.getInstance();
    new Crowller(url, analyzer);
    res.json(getResponseData(true));
  }

  @get("/showData")
  @use(checkLogin)
  showData(req: bodyRequest, res: Response): void {
    try {
      const position = path.resolve(__dirname, "../../data/course.json");
      const result = fs.readFileSync(position, "utf-8");
      res.json(getResponseData(JSON.parse(result)));
    } catch (e) {
      res.json(getResponseData(false, `数据不存在`));
    }
  }
}
